import { Injectable } from '@angular/core';
import { CanActivate, CanLoad, Route, Router } from '@angular/router';
import { AuthService } from './auth.service';

import { Observable } from 'rxjs/Observable';

@Injectable()
export class LoggedInGuard implements CanActivate, CanLoad {

  constructor (private auth: AuthService, private router: Router) {

  }

  canActivate () : boolean {
    return true;
  }

  canLoad (route: Route) : Observable<boolean> {
    let observable = this.auth.getUserInfo().map((data) => true, () => false);

    observable.subscribe(flag => {
      if (!flag) {
        this.router.navigate(['auth/sign-in', {from: route.path}], {replaceUrl: true});
      }
    });

    return observable;
  }

}
